// 这里的node代码会用babel处理
import express from 'express'
import path from 'path'
import fs from 'fs'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { matchRoutes } from 'react-router-dom'
import { getServerStore } from '../src/store/store'
import config from './config'
import routes from '../src/route/index'
import process from "process";
import render from "./render";

const app = express();

app.use(express.static("public"))

// 客户端触发的请求以/api 开头的统一在这里处理
app.use(
  '/api',
  createProxyMiddleware({ target: 'http://localhost:9090', changeOrigin: true })
);
const store = getServerStore()

const csrRender = (res) => {
  const filename = path.resolve(process.cwd(), "public/index.csr.html")
  const html = fs.readFileSync(filename, "utf-8")
  return res.send(html)
};

app.get("*", (req, res) => {
  // 可通过路径配置的方式实现 // !降级渲染
  // if (req.query._mode === "csr") {
  //   console.log("url参数开启csr降级");
  //   return csrRender(res)
  // }
  if (config.csr) {
    console.log('csr全局开关打开')
    return csrRender(res)
  }

  // 获取根据路由渲染出的组件，并拿到loadData方法获取数据
  const promises = [];

  const matchedRoutes = matchRoutes(routes, req.path) || [];

  matchedRoutes.forEach((item) => {
    if (item?.route?.loadData) {
      promises.push(item.route.loadData(store));
    }
    return item?.route?.loadData
  });
  // console.log(matchedRoutes);

  // 等待所有异步执行完毕
  Promise.allSettled(promises)
    .then(() => {
      const context = { css: [] };
      const html = render(store, req, context);
      if (context.statuscode) {
        // 状态的切换和页面跳转
        res.status(context.statuscode)
      }
      // 处理token过期跳转到登录页面
      if (context.action == "REPLACE") {
        res.redirect(301, context.url)
      }
      res.send(html)

    })
    .catch((e) => {
      console.log(e);
      // 这里处理报错页面
      res.send("报错了")
    })

})
app.listen(9093, () => {
  console.log("监听完毕!");
})